var serviceDetail;
$(function () {
    serviceDetail = new ServiceDetail();
});

var ServiceDetail = function () {
    this.init();
};
ServiceDetail.prototype = {
    goodsId: Number($('[name=goodsId]').val()), //服务ID
    memberId: Number($('[name=goodsMemberId]').val()), //发布该服务得会员ID
    goodsServerTimeList: [], //服务得服务时间段
    init: function () {
        var that = this;

        //百度分享插件
        window._bd_share_config = {
            "common": {
                "bdSnsKey": {},
                "bdText": "",
                "bdMini": "2",
                "bdMiniList": false,
                "bdPic": "",
                "bdStyle": "2",
                "bdSize": "16"
            },
            "share": {}
        };
        with (document) 0[(getElementsByTagName('head')[0] || body).appendChild(createElement('script')).src = 'http://bdimg.share.baidu.com/static/api/js/share.js?v=89860593.js?cdnversion=' + ~(-new Date() / 36e5)];

        //详情、评论选项卡
        $('#service_detail_header>ul>li').on('click', function () {
            var attrid = $(this).attr('attrid');
            $(this).addClass('hover').siblings().removeClass('hover');
            $('#' + attrid).fadeIn().siblings('.detail_common').hide();
        });

        // 主信息查询, 并渲染
        that.queryDataMain(that.goodsId, function (data) {
            //服务图片
            _.templateRender('#etalage', data.imageList, null, function ($elArray) {
                if($elArray.length != 0) {
                    $('#etalage .default').remove();
                }
                that.initPhoto();
            });
            //服务名称
            $('#goodsName').text(data['goodsName']);
            //服务标签
            var tagTemplate = '<span class="hover"><i class="icon_service icon_header"></i><i class="icon_footer">{{=tagName}}</i></span>';
            var tagListHtml = _.templateResolve(tagTemplate, data.tags);
            $('.server-tag-list').html(tagListHtml);
            //费用以及单位
            $('#shopPrice').text(data['shopPrice']);
            $('#goodsCompanyNote').text(data['goodsCompanyNote']);
            //服务时间段
            that.goodsServerTimeList = data['serverTimeList'];
            //服务方式
            $('#serverType i').filter(function () {
                return Number($(this).data('id')) == data.serverType;
            }).addClass('hover').siblings().remove();
            //是否收藏
            $('#collect em').text(data['isCollection'] ? '已收藏' : '收藏');
            //服务详情
            $('#detail_content').html(data['detailContent']);
            //根据服务是否已开启 显示购买等操作
            $('.handle, .tools')[data.isSale ? 'show' : 'hide']();
        });

        //卖家信息
        that.loadMemberInfoRequestAjax(function (data) {
            var member = data.result;
            var $container = $('.container_right');
            //头像
            $container.find('img').attr('src', member['image']);
            application.loadDefaultImgOnError($container);
            //姓名
            $container.find('.name').text(member['alias']);
            //标签
            var $tagPanel = $container.find('.people_intro .label');
            _.templateRender($tagPanel, member['specificTagList'], null, function ($elArray) {
                if($elArray.length > 0) $tagPanel.show();
            });
            //个人简介
            $container.find('.description').text(member['remark']);
            $container.fadeIn();

        });

        // my97日期插件加载
        $('#service_time').on('focus', function () {
            WdatePicker({minDate: '%y-%M-{%d}', dchanged: that.serverTimeChange});
        });
        //服务时间选择, 判断可选时间段
        $('#time_block i').on('click', function () {
            var $this = $(this);
            if (!$this.hasClass('can')) return false;
            $this.siblings().filter(function () {
                return $(this).hasClass('hover')
            }).removeClass('hover').addClass('can');
            $this.removeClass('can').addClass('hover');
        });

        //预约服务提交表单
        $('#subscribe').on('click', function () {
            if (!that.submitValidate()) {
                return false;
            }
            var serverTimeIdx = Number($('#time_block i').filter(function () {
                return $(this).hasClass('hover');
            }).first().data('idx'));
            var serverDate = moment($('#service_time').val(), 'YYYY年MM月DD日').toDate().getTime();
            window.location.href = window['ctx'] + '/toBuy?ids=' + that.goodsId + '&serverTimeIdx=' + serverTimeIdx + '&serverDate=' + serverDate;
        });

        //加入心愿车
        $('#addcart').on('click', function () {
            if (!that.submitValidate()) {
                return false;
            }
            that.addCartRequestAjax(function (data) {
                layer.msg('加入心愿车成功!');
            })
        });

        return that;
    },
    //立即购买, 加入心愿车 验证服务时间
    submitValidate: function () {
        var serviceTime = $('#service_time').val();
        var serverTimeArray = $('#time_block i.hover').map(function () {
            return $(this).data('idx');
        });
        if ($.trim(serviceTime) == '') {
            layer.tips('请选择服务时间!', $('#service_time'), {tips: [2, '#FF7800'], zIndex: 9999});
            return false;
        }
        if (serverTimeArray.length == 0) {
            layer.tips('请选择具体时间!', $('#time_block'), {tips: [2, '#FF7800'], zIndex: 9999});
            return false;
        }
        return true;
    },
    /**
     * 根据 服务得服务时间段, 共选择服务日期后, 哪些时间段是可选的.
     */
    serverTimeChange: function () {
        var that = serviceDetail;
        if (!that.goodsServerTimeList || that.goodsServerTimeList.length <= 0) {
            //TODO 由于导入数据没有服务时间段信息, 暂时放开时间段数据为空的服务
            $('#time_block i').removeClass('hover').removeClass('can').removeClass('none').addClass('can')
        } else {
            //日期插件选择的时间
            var selectedDateStr = $dp.cal.getNewDateStr();
            //获得moment对象
            var selectedDateMoment = moment(selectedDateStr, 'YYYY年MM月DD日');
            //获得选中日期是否星期几
            var weekDay = selectedDateMoment.weekday();
            var canChooseServerTime = _.where(that.goodsServerTimeList, {week: weekDay});
            $('#time_block i').removeClass('hover').removeClass('can').removeClass('none').addClass('none')
            $.each($(canChooseServerTime), function (idx, item) {
                $('#time_block i').filter(function () {
                    var $this = $(this);
                    var selectedRangeTimeStr = moment(selectedDateMoment.toDate().getTime()).format('YYYY-MM-DD ') + $this.data('end');
                    //过滤超时的时间段, 如 09:00-12:00, 当时当前系统时间已经是下午14点了.
                    var isInRange = window['serverTime'] < moment(selectedRangeTimeStr, 'YYYY-MM-DD hh:mm').toDate().getTime();
                    return $this.data('idx') == item['timeRange'] && isInRange;
                }).removeClass('none').addClass('can');
            });
        }
    },
    //相册插件加载
    initPhoto: function () {
        var that = this;
        //缩略图轮播
        $('#etalage').etalage({
            thumb_image_width: 300,
            thumb_image_height: 300,
            source_image_width: 900,
            source_image_height: 900,
            show_hint: false,
            show_icon: false,
            small_thumbs: 5,
            click_callback: function (image_anchor, instance_id) {
            }
        });
        //加载相册扩展模块
        layer.config({
            extend: 'extend/layer.ext.js'
        });
        //初始化layer
        layer.ready(function () {
            //使用相册
            layer.photos({
                photos: '.msg_imglist'
            });
        });
    },
    //评价信息分页查询
    commentPageQuery: function () {
        var that = this;
        that.$page = $("#goods-pagination").pagination({
            pageSize: 15,
            total: 100,
            debug: false,
            showInfo: false,
            showJump: true,
            showPageSizes: false,
            prevBtnText: '<i><</i> 上一页',
            nextBtnText: '下一页 <i>></i>',
            jumpBtnText: '确定',
            infoFormat: '共 {total} 条',
            noInfoText: '暂无数据',
            pageElementSort: ['$page', '$size', '$jump', '$info'],
            remote: {
                url: window['ctx'] + '/service/goods/list.json',
                params: that.getSearchParams(),
                totalName: 'result.total',
                pageIndexName: 'pageNum',
                pageSizeName: 'pageSize',
                success: function (data) {
                    _.templateRender(that.$serviceList, data.result.list);
                }
            }
        });
    },
    //服务主要信息查询
    queryDataMain: function (goodsId, callback) {
        var that = this;
        $.ajax({
            url: window['ctx'] + '/service/detail/data/main.json',
            type: 'get',
            dataType: 'json',
            data: {
                goodsId: goodsId
            }
        }).done(function (data) {
            callback && callback(data.result);
        }).fail(function (jqXHR, textStatus, errorThrown) {
            layer.msg('网络繁忙, 加载 服务 主信息失败, 请稍后再试!', {icon: 2});
        })
    },
    //发布该服务得会员信息查询
    queryDataMember: function (memberId, callback) {
        var that = this;
        $.ajax({
            url: window['ctx'] + '/service/detail/data/member.json',
            type: 'get',
            dataType: 'json',
            data: {
                goodsId: memberId
            }
        }).done(function (data) {
            callback && callback(data.result);
        }).fail(function (jqXHR, textStatus, errorThrown) {
            layer.msg('网络繁忙, 加载 服务 主信息失败, 请稍后再试!', {icon: 2});
        })
    },
    // 关注 会员接口
    //收藏服务接口
    // 加入购物车接口
    addCartRequestAjax: function (callback) {
        var that = this;
        $.ajax({
            url: window['ctx'] + '/car/add.json',
            type: 'post',
            dataType: 'json',
            data: {
                goodsId: that.goodsId,
                serverDate: moment($('#service_time').val(), 'YYYY年MM月DD日').toDate().getTime(),
                serverTimeIdx: Number($('#time_block i').filter(function () {
                    return $(this).hasClass('hover');
                }).first().data('idx'))
            }
        }).done(function (data) {
            callback && callback(data);
        }).fail(function (jqXHR, textStatus, errorThrown) {
            layer.msg('网络繁忙, 加入购物车失败, 请稍后再试!', {icon: 2});
        })
    },
    //立即购买地址
    //举报地址
    // 加载 服务 主信息
    /**
     * member 信息加载
     * @param callback
     */
    loadMemberInfoRequestAjax: function (callback) {
        var that = this;
        $.ajax({
            url: window['ctx'] + '/service/detail/member/info.json',
            type: 'get',
            dataType: 'json',
            data: {
                memberId: that.memberId
            }
        }).done(function (data) {
            callback && callback(data);
        }).fail(function (jqXHR, textStatus, errorThrown) {
            layer.msg('网络繁忙, , 加载卖家信息失败,请稍后再试!', {icon: 2});
        })
    }
};